<template>
    <div class="default-main ba-table-box position-management">
        <div class="left-panel">
            <el-card class="box-card">
                <template #header>
                    <div class="card-header">
                        <span>{{ t('部门列表') }}</span>
                    </div>
                </template>
                <div class="department-tree">
                    <div class="all-departments" @click="handleAllDepartments">
                        <span>{{ t('全部') }}</span>
                    </div>
                    <el-tree
                        :data="departmentTree"
                        :props="{ label: 'name', children: 'children' }"
                        @node-click="handleDepartmentSelect"
                        node-key="id"
                        default-expand-all
                        highlight-current
                        :expand-on-click-node="false"
                    ></el-tree>
                </div>
            </el-card>
        </div>

        <div class="right-panel">
            <el-alert class="ba-table-alert" v-if="baTable.table.remark" :title="baTable.table.remark" type="info" show-icon />

            <!-- 表格顶部菜单 -->
            <TableHeader
                :buttons="['refresh', 'add', 'edit', 'delete', 'comSearch', 'quickSearch', 'columnDisplay']"
                :quick-search-placeholder="t('Quick search placeholder', { fields: t('yxerp.position.quick Search Fields') })"
            ></TableHeader>

            <!-- 表格 -->
            <Table ref="tableRef"></Table>

            <!-- 表单 -->
            <PopupForm />
        </div>
    </div>
</template>

<script setup lang="ts">
import { onMounted, provide, ref } from 'vue'
import { useI18n } from 'vue-i18n'
import PopupForm from './popupForm.vue'
import { baTableApi } from '/@/api/common'
import { defaultOptButtons } from '/@/components/table'
import TableHeader from '/@/components/table/header/index.vue'
import Table from '/@/components/table/index.vue'
import baTableClass from '/@/utils/baTable'
import { getDepartmentTree } from '/@/api/backend/yxerp/department'

defineOptions({
    name: 'yxerp/position',
})

const { t } = useI18n()
const tableRef = ref()
const optButtons: OptButton[] = defaultOptButtons(['edit', 'delete'])
const departmentTree = ref<any[]>([])
const currentDepartmentId = ref<number | null>(null)

// 加载部门树
const loadDepartmentTree = async () => {
    try {
        const res = await getDepartmentTree()
        console.log(res)
        if (res.data && Array.isArray(res.data.list)) {
            departmentTree.value = res.data.list
            console.log(departmentTree.value)
        }
    } catch (error) {
        console.error('Failed to load department tree:', error)
    }
}

// 点击全部部门
const handleAllDepartments = () => {
    currentDepartmentId.value = null
    baTable.table.filter = {}
    baTable.getIndex()
}

// 点击部门树节点
const handleDepartmentSelect = (data: any) => {
    currentDepartmentId.value = data.id
    baTable.table.filter = { department_id: data.id }
    baTable.getIndex()
}

/**
 * baTable 内包含了表格的所有数据且数据具备响应性，然后通过 provide 注入给了后代组件
 */
const baTable = new baTableClass(
    new baTableApi('/admin/yxerp.Position/'),
    {
        pk: 'id',
        column: [
            { type: 'selection', align: 'center', operator: false },
            { label: t('yxerp.position.id'), fixed: true,  prop: 'id', align: 'center', width: 70, operator: 'RANGE', sortable: 'custom' },
            { label: t('yxerp.position.department_id'), prop: 'department_name', align: 'center', operatorPlaceholder: t('Fuzzy query'), operator: 'LIKE' },
            { label: t('yxerp.position.name'), prop: 'name', align: 'center', operatorPlaceholder: t('Fuzzy query'), operator: 'LIKE', sortable: false },
            { label: t('yxerp.position.code'), prop: 'code', align: 'center', operatorPlaceholder: t('Fuzzy query'), operator: 'LIKE', sortable: false },
            { label: t('yxerp.position.description'), prop: 'description', align: 'center', operatorPlaceholder: t('Fuzzy query'), operator: 'LIKE', sortable: false },
            { label: t('yxerp.position.status'), prop: 'status', align: 'center', render: 'tag', operator: 'eq', sortable: false, replaceValue:{ '0': '禁用', '1': '启用' }},
            { label: t('yxerp.position.sort'), prop: 'sort', align: 'center', operator: 'RANGE', sortable: false },
            { label: t('Operate'), align: 'center', width: 100, render: 'buttons', buttons: optButtons, operator: false },
        ],
        dblClickNotEditColumn: [undefined],
    },
    {
        defaultItems: { status: '1', sort: 1000 },
    }
)

provide('baTable', baTable)

onMounted(() => {
    baTable.table.ref = tableRef.value
    baTable.mount()
    baTable.getIndex()?.then(() => {
        baTable.initSort()
        baTable.dragSort()
    })
    loadDepartmentTree()
})
</script>

<style scoped lang="scss">
.position-management {
    display: flex;
    gap: 20px;
    
    .left-panel {
        width: 25%;
        min-width: 200px;
        
        .department-tree {
            max-height: calc(100vh - 200px);
            overflow-y: auto;
            
            .all-departments {
                padding: 10px 0;
                cursor: pointer;
                color: #409EFF;
                font-weight: bold;
                border-bottom: 1px solid #EBEEF5;
                margin-bottom: 10px;
                
                &:hover {
                    background-color: #F5F7FA;
                }
            }
        }
    }
    
    .right-panel {
        flex: 1;
        overflow: hidden;
    }
}
</style>
